package cn.hsrell.hscommunity.controller;

import cn.hsrell.hscommunity.common.entity.Result;
import cn.hsrell.hscommunity.entity.SubjectCategory;
import cn.hsrell.hscommunity.service.SubjectCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.google.common.base.Preconditions;

import javax.annotation.Resource;

/**
 * 题目分类(SubjectCategory)表控制层
 *
 * @author makejava
 * @since 2024-08-22 16:15:21
 */
@RestController
@RequestMapping("/subjectCategory/")
@Slf4j
public class SubjectCategoryController {
    @Resource
    private SubjectCategoryService subjectCategoryService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result<SubjectCategory> queryById(@PathVariable("id") Long id) {
        return Result.ok(this.subjectCategoryService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param subjectCategory 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public Result<Boolean> add(SubjectCategory subjectCategory) {
        try {
            log.info("新增数据:{}", subjectCategory);
            Preconditions.checkNotNull(subjectCategory.getCategoryType(), "分类类型不能为空");
            Preconditions.checkNotNull(subjectCategory.getParentId(), "父级分类不能为空");
            subjectCategoryService.insert(subjectCategory);
            return Result.ok(true);
        }catch (Exception e){
            log.info("新增数据失败:{}", e.getMessage());
            return Result.fail(e.getMessage());
        }

    }

    /**
     * 编辑数据
     *
     * @param subjectCategory 实体
     * @return 编辑结果
     */
    @PutMapping
    public Result<Boolean> edit(SubjectCategory subjectCategory) {
        try {
            log.info("编辑数据:{}", subjectCategory);
            Preconditions.checkNotNull(subjectCategory.getId(), "id不能为空");
            subjectCategoryService.update(subjectCategory);
            return Result.ok(true);
        }catch (Exception e){
            log.info("编辑数据失败:{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public Result<Boolean> deleteById(Long id) {
        try {
            log.info("删除分类, id为:{}", id);
            Preconditions.checkNotNull(id, "id不能为空");
            subjectCategoryService.deleteById(id);
            return Result.ok(true);
        }catch (Exception e){
            log.info("删除分类失败:{}", e.getMessage());
            return Result.fail(e.getMessage());
        }

    }

    //TODO 分页查询

}

